import {
	authPrivacyPolicyUrl,
	authLogin,
	privacyAgreementLatest,
	privacyAgreementSign,
	authDetails
} from "@/api/customApi.js"
import {
	setAuthorization,
	setUserId
} from "@/router/auth.js"

export async function loginFn(loginForm, successFn = () => {
	uni.showToast({
		title: "登录成功",
		icon: "success",
		success: function() {
			uni.switchTab({
				url: "/pages/index/index",
			});
		},
	});
}, errorFn = () => {
	uni.showToast({
		title: "登录失败",
		icon: "error",
	});
}) {
	const {
		code,
		data: {
			id
		}
	} = await authPrivacyPolicyUrl({
		type: '1',
		locale: 'zh-CN'
	})

	if (code == 200) {
		const {
			accessToken,
			code,
			userInfo
		} = await authLogin({
			userName: loginForm.userName,
			password: loginForm.password,
			privacyVer: id
		});
		if (code == '200') {
			setAuthorization(accessToken)
			setUserId(userInfo.userId)
			uni.setStorageSync('userName', loginForm.userName)
			uni.setStorageSync('password', loginForm.password)
			uni.setStorageSync('userInfo', userInfo)
			const {
				tenantList: [{
					tenantId = ''
				}]
			} = userInfo;

			await authDetailsFn(userInfo.userId, tenantId);

			return successFn?.(accessToken)
		} else if (code == '120000035') {
			uni.showToast({
				title: "账号/密码错误，请核对！",
				icon: "error",
			});
		} else {
			errorFn?.()
		}
	}
}

// 获取用户详情的，租户签名
async function authDetailsFn(userId, tenantId) {
	try {
		const data = await authDetails(userId, {
			tenantId
		});
		uni.$store.user.roleList = [];
		data.forEach(item => {
			if (!["24752AF4-CDED-45E1-BA14-813E7481BD50",
					"9FED519A-9993-4CCA-9305-3B6714C3A7C6"
				].includes(item.roleId)) {
				uni.$store.user.roleList.push(item.roleName)
			}
		})
	} catch (res) {
		if (res === "TENANT PRIVACY AGREEMENT FORBIDDEN") {
			const {
				data: {
					id
				}
			} = await privacyAgreementLatest({
				tenantId,
				type: 1,
				locale: 'zh-CN'
			})

			await privacyAgreementSign({
				tenantId: tenantId,
				privacyDocId: id,
				action: 1
			})

			authDetailsFn(userId, tenantId)
		}
	}
}